﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SP_Form_Suggestion
{
    class ScriptManager
    {
      
        private static string scriptRef()
        {
            return scriptRef(CONST.JQUERY_URL, CONST.JQUERY_UI_URL, CONST.JQUERY_UI_CSS_URL);
        }
        private static string scriptRef(string jqueryURL)
        {
            return scriptRef(jqueryURL, CONST.JQUERY_UI_URL, CONST.JQUERY_UI_CSS_URL);
        }
        private static string scriptRef(string jqueryURL, string jqueryUiURL)
        {
            return scriptRef(jqueryURL, jqueryUiURL, CONST.JQUERY_UI_CSS_URL);
        }
        private static string scriptRef(string jqueryURL, string jqueryUiURL, string cssURL)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(@"<script src=""" + jqueryURL + "\"type=\"text/javascript\"></script>");
            builder.Append(@"<script src=""" + jqueryUiURL + "\"type=\"text/javascript\"></script>");
            builder.Append(@"<link rel=""Stylesheet"" type=""text/css"" media=""all"" href=""" + cssURL + "\"/>");
            return builder.ToString();
        }

        private static string manageMainFunction(bool crossSiteScripting, string ajaxProxyURL, bool[] useAjaxProxyarr, string[] targetFormFieldNames,
                                        string[] sourceWebUrlArr, string[] sourceFieldNameArr, string[] sourceListGUID)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(@"<script type=""text/javascript"">");
            builder.Append(@"
                            // force cross-site scripting
                            jQuery.support.cors = " + (crossSiteScripting.ToString()).ToLower() + ";" +
                            @"
                            $(document).ready(function() {");
            for (int i = 0; i < targetFormFieldNames.Length; i++)
                builder.Append(@"
                                 $(""input[title=" + "'" + targetFormFieldNames[i] + "'" + @"]"").autocomplete({
                                        source: function(req,add)
                                                {
                                                    SoapService(req.term,add" + ",'Text'," +
                                                                "'" + sourceWebUrlArr[i] + "','"
                                                                    + sourceListGUID[i] + "','"
                                                                    + sourceFieldNameArr[i] +"'"+ ","
                                                                    + useAjaxProxyarr[i].ToString().ToLower()+","
                                                                    +"'" + ajaxProxyURL +"'" +@");
                                                }
                                 });"
                                );

            builder.Append("});");


            return builder.ToString();
        }
        private static string manageSOAPFunction()
        {
            string soap = @"
            function SoapService(value,handler,fieldType,webURL,listGUID,sourceFieldName,ajaxProxy,ajaxProxyURL) { 
               
                var serviceURL = ""/_vti_bin/lists.asmx"";
                var xmlCode = []; 
                xmlCode.push('<?xml version=""1.0"" encoding=""utf-8""?>'); 
                xmlCode.push('<soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">');
                if(ajaxProxy)
                    xmlCode.push(""<WebServiceURL>""+webURL+serviceURL+""</WebServiceURL>"");
                xmlCode.push('<soap12:Body>');
                xmlCode.push('<GetListItems xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">');
                xmlCode.push('<listName>'+listGUID+'</listName>');
                xmlCode.push(""<query><Query><Where><Contains><FieldRef Name='""+sourceFieldName+""'/> <Value Type='""+fieldType+""'>""+value+""</Value></Contains></Where></Query></query>"");
                xmlCode.push(""<viewFields><ViewFields><FieldRef Name='"" + sourceFieldName + ""'/></ViewFields></viewFields>"");
                xmlCode.push('<rowLimit>10</rowLimit>');
                xmlCode.push('</GetListItems>');
                xmlCode.push('</soap12:Body>');
                xmlCode.push('</soap12:Envelope>');
                xmlCode = xmlCode.join('');            
                
                var targetURL;
                if(ajaxProxy)
                    targetURL = ajaxProxyURL;
                else
                     targetURL = webURL+serviceURL;

                $.ajax({
                async: true,
                type: ""POST"",
                url: targetURL,
                contentType: ""text/xml; charset=\""utf-8\"""",
                data: xmlCode,
                dataType: ""xml"",
                complete: function(data,textStatus){
                    GetListItemsComplete(data,sourceFieldName,handler);
                    }
                
                });

               }";
            return soap;
        }
        private static string manageUpdateFunction()
        {
            string update = @"
                function GetListItemsComplete(xData,dataFieldName,handler) {

                    var results = [];
                    // firefox
                    if(xData.responseXML)
                    {
                        $(xData.responseXML).find(""z\\:row"").each(function () {
                            results.push($(this).attr(""ows_"" + dataFieldName));
                        });
                    }
                    // IE
                    else
                    {
                        $(xData.responseText).find(""z\\:row"").each(function () {
                            results.push($(this).attr(""ows_"" + dataFieldName));
                        });
                    }
                     
                    handler(results);
                    }";
            return update;
        }

        public static string createScript(  bool crossSiteScripting,
                                            string ajaxProxyURL,
                                            string[] targetFieldNameArr,
                                            string[] sourceSOAPWebUrlArr,
                                            string[] sourceFieldNameArr,
                                            string[] sourceListGUID,
                                            string JQuery_Url,
                                            string JQuery_UI_Url,
                                            string JQuery_UI_CSS_Url,
                                            bool[] ajaxProxyArr)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(scriptRef(JQuery_Url, JQuery_UI_Url, JQuery_UI_CSS_Url));
            builder.Append(manageMainFunction(crossSiteScripting,ajaxProxyURL,ajaxProxyArr,
                            targetFieldNameArr, sourceSOAPWebUrlArr, sourceFieldNameArr,sourceListGUID));
            builder.Append(manageSOAPFunction());
            builder.Append(manageUpdateFunction());
            builder.Append("</script>");
            return builder.ToString();

        }
    }
}
